<?php

declare(strict_types=1);

namespace Core\Package\Result;

use Core\HyperfUnit\Result;
use Core\Package\Attribute\Describe;
use Hyperf\Context\Context;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Zms\Exception\ExceptionCode;
use Zms\Unit\Json;

#[Describe(title: "Api响应工具")]
class Api
{

    #[Describe(title: "成功响应")]
    public function success(string $msg = '请求成功', mixed $data = null, mixed $debug = null): ResponseInterface
    {
        return $this->data(ExceptionCode::SUCCESS, $msg, $data, $debug);
    }


    #[Describe(title: "响应失败数据")]
    public function fail(string $msg = '请求失败', mixed $data = null, mixed $debug = null): ResponseInterface
    {
        return $this->data(ExceptionCode::MSG_FAIL, $msg, $data, $debug);
    }


    #[Describe(title: "响应错误数据")]
    public function error(string $msg = '系统错误', mixed $data = null, mixed $debug = null): ResponseInterface
    {
        return $this->data(ExceptionCode::ERROR, $msg, $data, $debug);
    }

    #[Describe(title: "数据响应")]
    public function data(int $code, string $msg, mixed $data = null, mixed $debug = null): ResponseInterface
    {
        if (is_null($data)) {
            $result = ['code' => $code, 'msg' => $msg, 'data' => null];
        } else {
            $result = ['code' => $code, 'msg' => $msg, 'data' => Result::toResponse($data)];
        }
        return $this->json($result);
    }


    /**
     * 响应JSON
     * @param array $data
     * @return ResponseInterface
     */
    public function json(array $data): ResponseInterface
    {
        /**
         * @var ResponseInterface $response
         */
        $response = Context::get(ResponseInterface::class);
        return $response->withStatus(200)->withHeader('Content-Type', 'application/json; charset=utf-8')->withBody(new SwooleStream(Json::encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)));
    }
}
